<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">

        <el-form-item label="学期" prop="className">
          <el-select
            v-model="queryParams.tetiId"
            clearable
            filterable
            size="small"
            style="width: 180px">
            <el-option
              v-for="dict in termTimeList"
              :key="dict.id"
              :label="dict.tetiBeginYear+'~'+dict.tetiEndYear"
              :value="dict.id"
            >
            <span style="float: left">{{ dict.tetiBeginYear+'~'+dict.tetiEndYear }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.tetiTerm==1?'一学期':'二学期' }}</span>
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="科目" >
          <el-select
            v-model="queryParams.subjId"
            clearable
            filterable
            size="small"
            style="width: 180px">
            <el-option
              v-for="dict in subjectList"
              :key="dict.id"
              :label="dict.subjName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="老师" prop="classDept">
          <el-select
            v-model="queryParams.syusId"
            clearable
            filterable
            size="small"
            style="width: 180px">
            <el-option
              v-for="dict in userOptions"
              :key="dict.id"
              :label="dict.username"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="classDept">
          <el-select
            v-model="queryParams.scclId"
            clearable
            filterable
            size="small"
            style="width: 180px">
            <el-option
              v-for="dict in classList"
              :key="dict.id"
              :label="dict.className"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排课是否冲突" prop="classDept">
          <el-checkbox v-model="queryParams.cpcoIsConflict" >是</el-checkbox>
        </el-form-item>
        <el-form-item label="课程时间" prop="classDept">
          <el-date-picker
            v-model="courseDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

        <el-table v-loading="loading" :data="coursePlanList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学期" align="center" prop="tetiId" width="170">
          <template slot-scope="scope">
              {{getTermTimeName(scope.row.tetiId)}}
          </template>
        </el-table-column>
        <el-table-column label="科目" align="center" prop="subjId" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
              {{getSubjectName(scope.row.subjId)}}
          </template>
        </el-table-column>
        <el-table-column label="班级" align="center" prop="scclId" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
              {{getClassName(scope.row.scclId)}}
          </template>
        </el-table-column>
        <el-table-column label="老师" align="center" prop="syusId">
          <template slot-scope="scope">
            {{ getTeacherName(scope.row.syusId) }}
          </template>
        </el-table-column>
        <el-table-column label="教室" align="center" prop="bsloId" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
              {{getLocationName(scope.row.bsloId)}}
          </template>
        </el-table-column>
        <el-table-column label="星期" align="center" prop="coplWeekDayNo" >
          <template slot-scope="scope">
              <span v-if="scope.row.coplWeekDayNo==1">周一</span>
              <span v-if="scope.row.coplWeekDayNo==2">周二</span>
              <span v-if="scope.row.coplWeekDayNo==3">周三</span>
              <span v-if="scope.row.coplWeekDayNo==4">周四</span>
              <span v-if="scope.row.coplWeekDayNo==5">周五</span>
              <span v-if="scope.row.coplWeekDayNo==6">周六</span>
              <span v-if="scope.row.coplWeekDayNo==7">周日</span>
          </template>
        </el-table-column>
        <el-table-column label="排课是否冲突" align="center" prop="cpcoConflictType">
          <template slot-scope="scope">
              <el-tag v-if="scope.row.cpcoConflictType=='teacher'" >教师冲突</el-tag>
              <el-tag v-if="scope.row.cpcoConflictType=='classRoom'">场地冲突</el-tag>
              <el-tag v-if="scope.row.cpcoConflictType=='teacAndRoom'">教师和冲突</el-tag>
              <el-tag v-if="scope.row.cpcoConflictType==''" type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排课周次" align="center" prop="coplWeekNo" >
        </el-table-column>

        <el-table-column label="课程开始时间" align="center" width="160" prop="coplBeginWeekNo"  >
          <template slot-scope="scope">
            {{ parseTime(scope.row.courBeginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="课程结束时间" align="center" prop="coplEndWeekNo" width="160">
          <template slot-scope="scope">
            {{ parseTime(scope.row.courEndTime) }}
          </template>
        </el-table-column>
        <el-table-column label="节次" align="center" prop="coseId" >
        </el-table-column>
        <el-table-column label="课程创建时间" align="center" width="160" prop="coplCourseGennerStatus">
          <template slot-scope="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="修改" v-hasPermi="['class:info:edit']" placement="top">
              <el-button size="mini" circle type="success" icon="el-icon-edit" @click="changeClaTime(scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" v-hasPermi="['class:info:del']">
              <el-button size="mini" circle type="danger" icon="el-icon-delete"  @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />



      <el-dialog :title="claTimeTitle" width="400px" :visible.sync="showClsTime">
      <el-form :model="classTimeForm" ref="classTimeForm"  :rules="rules" label-width="90px">
        <el-form-item label="学期" >
          {{getTermTimeName(classTimeForm.tetiId)}}
          <!-- {{ tetiItem.tetiBeginYear +'~'+ tetiItem.tetiEndYear}} {{ tetiItem.tetiTerm==1?'一学期':'二学期' }} -->
        </el-form-item>
        <el-form-item label="班级" prop="scclId">
            <el-select v-model="classTimeForm.scclId" clearable filterable style="width:100%">
              <el-option v-for="item in classList" :label="item.className" placeholder="班级" :value="item.id" :key="item.id">
                <span style="float: left">{{ item.className }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.classTeacherId }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="科目" prop="subjId">
          <el-select
            v-model="classTimeForm.subjId"
            clearable
            filterable
            size="small"
            style="width: 100%">
            <el-option
              v-for="dict in subjectList"
              :key="dict.id"
              :label="dict.subjName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排课日期" prop="coplWeekDayNo">

          <el-date-picker @change="getWeekDayNo"
            v-model="classTimeForm.courseDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>

        </el-form-item>
        <el-form-item label="任课老师" prop="syusId">
           <el-select v-model="classTimeForm.syusId" filterable placeholder="请选择" style="width:100%">
             <el-option
                     v-for="item1 in userOptions"
                     :key="item1.id"
                     :label="item1.username"
                     :value="item1.id"
             />
           </el-select>
         </el-form-item>
        <el-form-item label="排课节次" prop="coseId">
          <el-select v-model="classTimeForm.coseId" filterable placeholder="请选择" style="width:100%">
             <el-option
                     v-for="item1 in coseList"
                     :key="item1.id"
                     :label="item1.coseBeginTime+'~'+item1.coseEndTime"
                     :value="item1.id"
             >
              <span style="float: left">{{ item1.coseBeginTime+'~'+item1.coseEndTime }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ '第'+item1.coseCode+'节课' }}</span>
             </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课教室" prop="bsloId">
           <el-select v-model="classTimeForm.bsloId" filterable placeholder="请选择" style="width:100%">
             <el-option
                     v-for="item1 in classRoomList"
                     :key="item1.id"
                     :label="item1.locationName"
                     :value="item1.id"
             >
              <span style="float: left">{{ item1.locationName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.levelName }}</span>
             </el-option>
           </el-select>
         </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    </div>
  </template>

  <script>
  import { findSchoolClassPageList, deleteSchoolClassInfo,} from "@/api/classManage/classInfo";
  import { coursePageList} from "@/api/course/coursePlan";
  import { sessionsList} from "@/api/baseData/sectiontimemanagement";

  import { getClassTeacherList } from "@/api/system/user";
  import { findBaseSubjectPageList} from "@/api/baseData/profession";
  import { listTermtime } from "@/api/system/termtime.js";
  import { originalData} from "@/api/studentInfo/infoMaintenance/index";
  import { findBaseSpaceLocationPageList} from "@/api/baseData/siteManagement";
  import claTimeCalendar from '@/views/course/timetable/claTimeCalendar'
  import {subjectList} from "@/api/educational/subject.js";
  import moment from 'moment'
  import { createOrUpdateCourse,deleteCorse} from "@/api/course/coursePlan";

  export default {
    name: "coursePlan",
    components: {
        claTimeCalendar
    },
    data() {
      return {
        checkList:[],
        teacherClassTimeVisible:false,
        activeName:'first',
        // 遮罩层
        loading: true,
        // 选中数组
        rowList: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        stuCount: 0,
        // 字典表格数据
        classList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 班主任
        userOptions: [],
        // 状态数据字典
        statusOptions: [],
        // 班级所属部门
        classDeptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          className: undefined,
          status: undefined,
          classDept:undefined,
          cpcoIsConflict:null
        },
        // 表单参数
        form: {
          coplWeekDayNoList: []
        },
        subjectList:[],
        termTimeList:[],
        classGradeList:[],
        studentList:[],
        studentTotal:[],
        studentParam:{
          pageSize:10,
          pageNum:1
        },
        studentLoading:false,
        studentDialogVisible:false,
        classRoomList:[],
        coursePlanList:[],
        coseList:[],
        classId:null,
        showTabS:false,
        courseDate:[],
        //排课，调课表单内容
        classTimeForm:{
          coplWeekDayNoList:[]
        },
        showClsTime:false,
        columnTitles:'',
        claTimeTitle:'',
        rules: {
          subjId: [
            { required: true, message: "科目不能为空", trigger: "blur" }
          ],
          scclId: [
            { required: true, message: "班级不能为空", trigger: "blur" }
          ],
          syusId:[
            { required: true, message: "任课老师不能为空", trigger: "blur" }
          ],
          bsloId:[
            { required: true, message: "上课教室不能为空", trigger: "blur" }
          ],
          coseId:[
            { required: true, message: "排课节次不能为空", trigger: "blur" }
          ],
          coplWeekDayNo:[
            { required: true, message: "排课日期不能为空", trigger: "blur" }
          ]
        },
      };
    },
    created() {
      this.getList()
      this.getLocationList()
      this.getClassList();
      this.getClassTeacherList();
      this.getSubjectList()
      this.getTermTimeList()
      this.getCoseList()
    },
    methods: {
      cancel(){
        this.showClsTime = false
      },
      getWeekDayNo(val){
        console.log(val)
        this.classTimeForm.tetiId
        let termBeginDate = ''
        let termEndDate = ''
        let currDate=val
        for(let i=0;i<this.termTimeList.length;i++){
          if(this.termTimeList[i].id==this.classTimeForm.tetiId){
            termBeginDate = this.termTimeList[i].tetiTermBeginDate
            termEndDate = this.termTimeList[i].tetiTermEndDate
          }
        }
        termBeginDate =  this.parseTime(termBeginDate,'{y}-{m}-{d}')
        termEndDate = this.parseTime(termEndDate,'{y}-{m}-{d}')
        //当前时间时星期几
        let weekdayNo = moment(val).weekday();
        if(weekdayNo==0){//周日
          weekdayNo = 7
        }
        console.log(weekdayNo)
        var d1 = new Date(termBeginDate);
        var d2 = new Date(termEndDate);
        var d3 = new Date(currDate);
        var dt1 = d1.getTime();
        var dt2 = d2.getTime();
        var dt3 = d3.getTime();
        if(dt3<dt1 || dt3>dt2){
          this.classTimeForm.courseDate = null
          this.$message({
            message: '选择日期不在当前学期内',
            type: 'warning'
          });
          return
        }
        const termWeekNo = this.termWeekDayNo(dt1,dt2,dt3,weekdayNo)

        this.classTimeForm.coplWeekDayNo = weekdayNo
        this.classTimeForm.coplWeekNo = termWeekNo
      },
      termWeekDayNo(dt1,dt2,dt3,weekdayNo){//获取当前时间时在学期的第几周
        //当前学期的周数
        const termWeekNum =  Math.ceil(Math.abs(dt2 - dt1) / 1000 / 60 / 60 / 24 / 7);
        console.log(termWeekNum);
        //计算当前时间到学期结束时间的周数
        const currTermWeekNum =  Math.ceil(Math.abs(dt2 - dt3) / 1000 / 60 / 60 / 24 / 7);
        console.log(currTermWeekNum);
        //减周数时当前周不能减
        let currDateWeekNo
        if(weekdayNo==7){
          currDateWeekNo = termWeekNum-currTermWeekNum
        }else{
          currDateWeekNo = termWeekNum-currTermWeekNum +1
        }
        console.log(currDateWeekNo)
        return currDateWeekNo


      },

      changeClaTime(claTime) {
        this.showClsTime = true
        this.claTimeTitle = '调课'
        const courBeginTime = this.parseTime(claTime.courBeginTime,'{y}-{m}-{d}')
        this.classTimeForm={
          id:claTime.id,
          scclName:claTime.claName,
          coplId: Number(claTime.coplId),
          subjId:Number(claTime.subjId),
          scclId:Number(claTime.scclId),
          coseId:Number(claTime.coseId),
          syusId:Number(claTime.syusId),
          bsloId:Number(claTime.bsloId),
          coplWeekDayNo:Number(claTime.coplWeekDayNo),
          coplWeekNo: claTime.coplWeekNo,
          tetiId:claTime.tetiId,
          courseDate: courBeginTime
        }

        console.log(this.classTimeForm)
      },
      getTermTimeName(id){
        //学期名称
        for(let i=0;i<this.termTimeList.length;i++){
          if(this.termTimeList[i].id==id){
            let str=''
            if(this.termTimeList[i].tetiTerm==1){
              str = '第一学期'
            }
            if(this.termTimeList[i].tetiTerm==2){
              str = '第二学期'
            }
            return this.termTimeList[i].tetiBeginYear+'~'+this.termTimeList[i].tetiEndYear+'['+str+']'
          }
        }
      },
      cancel(){
        this.showClsTime = false
      },
      submitForm(){
        this.$refs["classTimeForm"].validate(valid => {
          if (valid) {
            createOrUpdateCourse(this.classTimeForm).then(resp=>{
                this.msgSuccess("提交成功");
                this.showClsTime = false
                this.getList()
            })
          }
        })
      },
      openTeacherClassTime(){
        //打开老师课表
        this.teacherClassTimeVisible = true
      },
      handleClick(tab, event) {
        //切换tab
        console.log(tab, event);
        console.log(tab.name)
        if(tab.name=='second'){
          this.classId = this.classList[0].id+''
          this.queryParams.scclId = this.classList[0].id
          this.showTabS = true
        }else{
          this.showTabS = false
        }
      },
      getCoseList(){
        sessionsList({pageSize:20,pageNum:1}).then(resp=>{
          for(let i=0;i<resp.data.list.length;i++){
            this.coseList = resp.data.list
          }
        })
      },
      getTeacherName(id){
        //老师名称
        for(let i=0;i<this.userOptions.length;i++){
          if(this.userOptions[i].id==id){
            return this.userOptions[i].username
          }
        }
      },
      getClassName(id){
        //班级名称
        for(let i=0;i<this.classList.length;i++){
          if(this.classList[i].id==id){
            return this.classList[i].className
          }
        }
      },
      getSubjectName(id){
        //科目名称
        for(let i=0;i<this.subjectList.length;i++){
          if(this.subjectList[i].id==id){
            return this.subjectList[i].subjName
          }
        }
      },
      getTermTimeName(id){
        //学期名称
        for(let i=0;i<this.termTimeList.length;i++){
          if(this.termTimeList[i].id==id){
            let str=''
            if(this.termTimeList[i].tetiTerm==1){
              str = '第一学期'
            }
            if(this.termTimeList[i].tetiTerm==2){
              str = '第二学期'
            }
            return this.termTimeList[i].tetiBeginYear+'~'+this.termTimeList[i].tetiEndYear+'['+str+']'
          }
        }
      },
      getLocationName(id){
        //获取教室名称
        for(let i=0;i<this.classRoomList.length;i++){
          if(this.classRoomList[i].id==id){
            return this.classRoomList[i].levelName
          }
        }
      },
      getList(){
          this.loading = true
          if(this.courseDate){
            this.queryParams.courBeginAreaTime=this.courseDate[0]
            this.queryParams.courEndAreaTime=this.courseDate[1]
          }else{
            this.queryParams.courBeginAreaTime=''
            this.queryParams.courEndAreaTime=''
          }
          if(!this.queryParams.cpcoIsConflict){
            this.queryParams.cpcoIsConflict = null
          }
          coursePageList(this.queryParams).then(resp=>{
            this.coursePlanList = resp.data.list
            this.total = resp.data.total;
            this.loading = false;
          })


      },
      getLocationList(){
        findBaseSpaceLocationPageList({pageNum:1,pageSize:1000,locationType: 4}).then(resp=>{
          this.classRoomList = resp.data.list
        })
      },
      handleStudent(row){
        this.studentDialogVisible = true
        this.studentParam.classId = row.id
        this.getStudentList()
      },
      getStudentList() {
        this.studentLoading = true
        originalData(this.studentParam).then((res) => {
          console.log(res);
          this.studentList = res.data.list;
          this.studentTotal = res.data.total;
          this.studentLoading = false
        });
      },
      getDictLabel(list,value){
         for(let i=0;i<list.length;i++){
          if(list[i].dictValue==value){
            return list[i].dictLabel
          }
         }
      },
      getTermTimeList() {
        //查询学期
        this.loading = true;
        listTermtime({pageSize:100,pageNum:1,status:1}).then(response => {
            this.termTimeList = response.data.list;

          }
        );
      },
      getSubjectList(){
        //查询专柜
        subjectList({pageSize:100,pageNum:1,status:1}).then(response =>{
          this.subjectList = response.data.list
        })
      },
      /** 查询班级列表 */
      getClassList() {
        this.loading = true;
        findSchoolClassPageList({pageSize:200,pageNum:1,status:1,isGraduation:0}).then(response => {
            this.classList = response.data.list;
          }
        );
      },
      getClassTeacherList(){
        getClassTeacherList().then(response => {
          this.userOptions = response.data;
        });
      },
      // 字典设备状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 字典设备状态字典翻译
      classDeptFormat(row, column) {
        return this.selectDictLabel(this.classDeptOptions, row.classDept);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.showClsTime = false;
        console.log(this.open);
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          className: undefined,
          classTeacherId: undefined,
          status: "1",
          classDept:undefined,
          coplWeekDayNoList: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.queryParams={
          pageSize:10,
          pageNum:1,
          tetiId:null,
          subjId:null,
          syusId:null,
          scclId:null,
          cpcoIsConflict:null
        }
        this.courseDate=[]
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加班级信息";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        console.log(selection)
        this.rowList = selection

        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.open = true
        this.form = row
        this.form.classSubject = row.classSubject?Number(row.classSubject):null
        this.form.semester = row.semester?Number(row.semester):null
        // this.form.classTeacherId = Number(row.classTeacherId)
        // this.form.assistantTeacharId = Number(row.assistantTeacharId)
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除班级编号为"' + ids + '"的数据项?', "警告", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }).then(function() {
                  return deleteCorse(row.id);
                }).then(() => {
                  this.getList();
                  this.msgSuccess("删除成功");
                }).catch(function() {});




      },

    }
  };
  </script>
